package com.demo.fragment;

import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import com.demo.R;
import com.demo.domain.Contact;

/**
 * Author: Alexey Tokan
 * Date: 26.07.12
 * Time: 10:32
 */
public class EditForm extends Fragment {

    private EditText firstNameEdit;
    private EditText lastNameEdit;
    private EditText phoneEdit;
    private EditText emailEdit;
    private ImageView photoView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.edit_form, container, false);
        firstNameEdit = (EditText) view.findViewById(R.id.first_name);
        lastNameEdit = (EditText) view.findViewById(R.id.last_name);
        phoneEdit = (EditText) view.findViewById(R.id.phone);
        emailEdit = (EditText) view.findViewById(R.id.email);
        photoView = (ImageView) view.findViewById(R.id.contact_photo);
        Bundle bundle = savedInstanceState;
        if ((bundle != null
                || (bundle = getArguments()) != null
                || (bundle = getActivity().getIntent().getExtras()) != null) && bundle.containsKey(Contact.CONTACT)) {
            Contact contact = (Contact) bundle.get(Contact.CONTACT);
            fillFields(contact);
        }
        return view;
    }

    /**
     * Fill fields with contact data
     * @param contact contact which data with which fragment fields would be filled.
     */
    public void fillFields(Contact contact) {
        firstNameEdit.setText(contact.getFirstName());
        lastNameEdit.setText(contact.getLastName());
        phoneEdit.setText(contact.getPhone());
        emailEdit.setText(contact.getEmail());
        if (contact.getPhone() != null) {
            photoView.setImageURI(Uri.parse(contact.getPhone()));
        }
    }

    /**
     * Retrieve data from fragment fields and fill contact with it.
      * @param contact contact which will be filled with data
     */
    public void saveFieldToContact(Contact contact) {
        contact.setFirstName(firstNameEdit.getText().toString());
        contact.setLastName(lastNameEdit.getText().toString());
        contact.setPhone(phoneEdit.getText().toString());
        contact.setEmail(emailEdit.getText().toString());
        // contact photo sets when image was selected
    }

}
